package com.asiainfo.integration.actions;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.jms.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

/**
 * Usage:
 *
 * @author Charkey
 * @date 2015/11/19
 */
@WebServlet(urlPatterns = "/message/send", asyncSupported = true)
public class SendMsgAction extends HttpServlet {

    public static final Logger INFO_LOG = Logger.getLogger(SendMsgAction.class);

    private static final String INITIAL_CONTEXT_FACTORY = "com.tibco.tibjms.naming.TibjmsInitialContextFactory";

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        MultipartHttpServletRequest multipartRequest = resolver.resolveMultipart(request);

        String connection_url = multipartRequest.getParameter("connection_url").trim();
        String connection_factory = multipartRequest.getParameter("connection_factory").trim();
        String username = multipartRequest.getParameter("username").trim();
        String password = multipartRequest.getParameter("password").trim();
        String queue_name = multipartRequest.getParameter("queue_name").trim();
        String message_content = multipartRequest.getParameter("message_content");
        String rollback_mark = multipartRequest.getParameter("rollback_mark");
        String review_message = multipartRequest.getParameter("review_message");
        String interfaceName = multipartRequest.getParameter("interface_name");
        String[] prop_names = multipartRequest.getParameterValues("prop_name");
        String[] prop_values = multipartRequest.getParameterValues("prop_value");

        MultipartFile messageFile = multipartRequest.getFile("message_file");
        String messageFromFile = null;
        if (messageFile != null) {
            messageFromFile = IOUtils.toString(messageFile.getInputStream());
        }

        request.setAttribute("connection_url", connection_url);
        request.setAttribute("connection_factory", connection_factory);
        request.setAttribute("username", username);
        request.setAttribute("password", password);
        request.setAttribute("queue_name", queue_name);
        request.setAttribute("prop_names", prop_names);
        request.setAttribute("prop_values", prop_values);

        if (review_message != null && review_message.equals("on")) {
            if (message_content != null && !message_content.equals("")) {
                request.setAttribute("message_content", message_content);
            } else {
                request.setAttribute("message_content", messageFromFile);
            }
        }

        request.setAttribute("interface_name", interfaceName);

        try {
            Properties tibcoProperties = new Properties();
            tibcoProperties.put(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT_FACTORY);
            tibcoProperties.put(Context.PROVIDER_URL, connection_url);
            tibcoProperties.put(Context.SECURITY_PRINCIPAL, username);
            tibcoProperties.put(Context.SECURITY_CREDENTIALS, password);
            Context context = new InitialContext(tibcoProperties);
            QueueConnectionFactory factory = (QueueConnectionFactory) context.lookup(connection_factory);
            Connection connection = factory.createConnection(username, password);
            Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
            Queue queue = session.createQueue(queue_name);

            MessageProducer sender = session.createProducer(queue);
            TextMessage messageToSend = session.createTextMessage();

            for (int i = 0; i < prop_names.length; i++) {
                if (!StringUtils.isEmpty(prop_names[i])) {
                    messageToSend.setObjectProperty(prop_names[i], prop_values[i]);
                }
            }

            if (message_content != null && !message_content.equals("")) {
                messageToSend.setText(message_content);
            } else {
                messageToSend.setText(messageFromFile);
            }

            sender.send(messageToSend);

            if (rollback_mark != null && rollback_mark.equals("on")) {
                session.rollback();
            }

            sender.close();
            request.setAttribute("is_error", false);
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            request.setAttribute("error_message", formatter.format(new Date()) + " Message successfully send!");

            if (rollback_mark != null && rollback_mark.equals("on")) {
                request.setAttribute("error_message", request.getAttribute("error_message").toString() + " And rollback!");
            }
            session.commit();
            request.getRequestDispatcher("/WEB-INF/pages/send.jsp").forward(request, response);
        } catch (NamingException e) {
            e.printStackTrace();
            request.setAttribute("error_message", e.getMessage());
            request.setAttribute("is_error", true);
            request.getRequestDispatcher("/WEB-INF/pages/send.jsp").forward(request, response);
        } catch (JMSException e) {
            e.printStackTrace();
            request.setAttribute("error_message", e.getMessage());
            request.setAttribute("is_error", true);
            request.getRequestDispatcher("/WEB-INF/pages/send.jsp").forward(request, response);
        }
    }

}
